//package com.plian.system.service.fr.internalauditmanagement.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.config.YthTaskObserver;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dao.sys.file.FileDao;
//import com.plian.system.dto.fr.internalauditmanagement.IamAuditContactDTO;
//import com.plian.system.dto.fr.internalauditmanagement.IamInternalAuditOrganizationDTO;
//import com.plian.system.dto.fr.internalauditmanagement.IamWorkSystemDetailDTO;
//import com.plian.system.entity.fr.internalauditmanagement.IamAuditContact;
//import com.plian.system.entity.fr.internalauditmanagement.IamInternalAuditOrganization;
//import com.plian.system.entity.fr.internalauditmanagement.IamWorkSystemDetail;
//import com.plian.system.entity.sys.Org;
//import com.plian.system.mapper.fr.internalauditmanagement.IamAuditContactMapper;
//import com.plian.system.mapper.fr.internalauditmanagement.IamInternalAuditOrganizationMapper;
//import com.plian.system.mapper.fr.internalauditmanagement.IamWorkSystemDetailMapper;
//import com.plian.system.model.ObjResult;
//import com.plian.system.model.R;
//import com.plian.system.config.exception.MyRuntimeException;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.service.fr.internalauditmanagement.IamAuditContactService;
//import com.plian.system.service.fr.internalauditmanagement.IamInternalAuditReportService;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.service.sys.user.ISysUserService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.service.yth.ISznbAuditPlanService;
//import com.plian.system.vo.fr.internalauditmanagement.IamAuditContactVO;
//import com.plian.system.vo.fr.internalauditmanagement.IamInternalAuditOrganizationVO;
//import com.plian.system.wrapper.fr.internalauditmanagement.IamAuditContactWrapper;
//import com.plian.system.wrapper.fr.internalauditmanagement.IamInternalAuditOrganizationWrapper;
//import com.plian.system.wrapper.fr.internalauditmanagement.IamWorkSystemDetailWrapper;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
///**
// * @author jiatp
// * @create 2023-02-20
// **/
//@Service
//@Slf4j
//@AllArgsConstructor
//public class IamInternalAuditReportServiceImpl extends BaseServiceImpl<IamInternalAuditOrganizationMapper, IamInternalAuditOrganization> implements IamInternalAuditReportService, BaseFlowService {
//
//
//    private FormWorkflowService formWorkflowService;
//
//    private IFormCodeService formCodeService;
//    private final IamInternalAuditOrganizationWrapper auditOrganizationWrapper;
//
//    private final IamAuditContactWrapper auditContactWrapper;
//
//    private final IamAuditContactMapper auditContactMapper;
//
//    private final IamWorkSystemDetailMapper systemDetailMapper;
//
//    private final IamWorkSystemDetailWrapper systemDetailWrapper;
//
//    private final IamAuditContactService auditContactService;
//    private final FileService fileService;
//
//    private final FileDao fileDao;
//    private final ISysUserService userService;
//    private IOrgService orgService;
//    private ISznbAuditPlanService ythAuditPlanService;
//
//
//    @Override
//    @Transactional(rollbackFor = Throwable.class)
//    public R submit(IamInternalAuditOrganizationVO recordVO) {
//        try {
//            boolean flag = false;
//            Org org = orgService.getById(TokenUtil.getTokenOrgId());
//            IamInternalAuditOrganization auditOrganization = auditOrganizationWrapper.voToEntity(recordVO);
//            if (auditOrganization.getId() == null) {
//                flag = true;
//                auditOrganization.setFormType(String.valueOf(FormTypeConstant.IAM_AUDIT_YEAR_REPORT));
//                auditOrganization.setCode(formCodeService.getCode(FormTypeConstant.IAM_AUDIT_YEAR_REPORT));
//            }
//            boolean result = super.saveOrUpdate(auditOrganization);
//            if (flag) {
//                fileService.saveAll(String.valueOf(auditOrganization.getId()), recordVO.getDocList());
//            } else {
//                fileService.edit(String.valueOf(auditOrganization.getId()), recordVO.getDocList());
//
//            }
//            /**
//             * 保存/修改内审联系人
//             */
//            List<IamAuditContactVO> auditContactVOList = recordVO.getAuditContacts();
//            List<IamAuditContact> iamAuditContactsList = auditContactWrapper.voToEntity(auditContactVOList);
//            IamInternalAuditOrganization finalAuditOrganization = auditOrganization;
//            iamAuditContactsList.forEach(item -> {
//                item.setAuditId(finalAuditOrganization.getId());
//                item.setEnterpriseId(finalAuditOrganization.getEnterpriseId());
//                item.setEnterpriseName(org.getName());
//            });
//            auditContactService.saveList(iamAuditContactsList);
//            List<IamAuditContact> delItems = iamAuditContactsList.stream().filter(item -> item.getIsDeleted() == 1).collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(delItems)) {
//                List<Long> ids = delItems.stream().map(IamAuditContact::getId).collect(Collectors.toList());
//                auditContactService.deleteLogic(ids);
//            }
//            return R.success();
//        } catch (Exception e) {
//            log.error("error-submit:" + e.getMessage());
//            throw new MyRuntimeException(new ObjResult("操作失败"));
//
//        }
//    }
//
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    public Boolean finish(String id) {
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        return handleStatus(Long.valueOf(id), formState);
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        List<IamInternalAuditOrganization> reportRecords = list(new LambdaQueryWrapper<IamInternalAuditOrganization>()
//                .in(IamInternalAuditOrganization::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
//        List<IamInternalAuditOrganizationVO> auditOrganizationVOList = auditOrganizationWrapper.entityToVO(reportRecords);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(auditOrganizationVOList)) {
//                for (IamInternalAuditOrganizationVO vo : auditOrganizationVOList) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getEnterpriseName());
//                    pd.put("APPLICANTNAME", vo.getCreateUser());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getEnterpriseId());
//                    pd.put("formType", FormTypeConstant.IAM_AUDIT_YEAR_REPORT);
//                    pd.put("orgName", vo.getEnterpriseName());
//                    pageDataList.add(pd);
//                }
//            }
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.IAM_AUDIT_YEAR_REPORT);
//    }
//
//    @Override
//    public IamInternalAuditOrganizationDTO detail(IamInternalAuditOrganizationVO auditOrganizationVO) {
//
//        IamInternalAuditOrganizationDTO auditOrganizationDTO = null;
//        List<IamAuditContactDTO> iamAuditContactDTOS = new ArrayList<>();
//        List<IamWorkSystemDetailDTO> iamWorkSystemDetailDTOS = new ArrayList<>();
//
//        if (auditOrganizationVO.getId() != null) {
//
//            IamInternalAuditOrganization auditOrganization = getById(auditOrganizationVO.getId());
//            if (auditOrganization != null) {
//                auditOrganizationDTO = auditOrganizationWrapper.entityToDto(auditOrganization);
//
//                List<HashMap> docList = new ArrayList<>();
//                //内审工作资料
//                try {
//                    List<PageData> list = fileDao.findParentId(auditOrganizationDTO.getId().toString());
//                    list.forEach(e -> {
//                        docList.add(e);
//                    });
//                    auditOrganizationDTO.setDocList(docList);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                //查询审计联系人
//                List<IamAuditContact> iamAuditContacts = auditContactMapper.selectList(new LambdaQueryWrapper<IamAuditContact>()
//                        .eq(IamAuditContact::getAuditId, auditOrganization.getId()));
//
//                if (CollectionUtil.isNotEmpty(iamAuditContacts)) {
//                    iamAuditContactDTOS = auditContactWrapper.entityToDto(iamAuditContacts);
//                }
//                //查询相关制度
//                List<IamWorkSystemDetail> systemDetailList = systemDetailMapper.selectList(new LambdaQueryWrapper<IamWorkSystemDetail>()
//                        .eq(IamWorkSystemDetail::getEnterpriseId, auditOrganization.getEnterpriseId()));
//
//                systemDetailList.stream().filter(item -> {
//                    String currentMonth = DateUtil.format(new Date(), DateUtil.PATTERN_MONTH);
//                    String createTime = DateUtil.format(item.getCreateTime(), DateUtil.PATTERN_MONTH);
//                    if (currentMonth.equals(createTime)) {
//                        return true;
//                    }
//                    return false;
//                }).collect(Collectors.toList());
//
//
//                if (CollectionUtil.isNotEmpty(systemDetailList)) {
//                    iamWorkSystemDetailDTOS = systemDetailWrapper.entityToDto(systemDetailList);
//                }
//
//            }
//
//        }
//        //内审联系人
//        auditOrganizationDTO.setAuditContacts(iamAuditContactDTOS);
//        auditOrganizationDTO.setSystemDetailList(iamWorkSystemDetailDTOS);
//        return auditOrganizationDTO;
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            IamInternalAuditOrganization auditOrganization = getById(id);
//            if (updateStatus == FormStatusConstant.FINISH) {
//                auditOrganization.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                auditOrganization.setApprovedTime(now);
//            }
//            auditOrganization.setStatus(updateStatus);
//            updateById(auditOrganization);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            IamInternalAuditOrganization auditOrganization = getById(id);
//            if (auditOrganization == null) {
//                return false;
//            } else if (auditOrganization.getStatus() != null &&
//                    (auditOrganization.getStatus() != FormStatusConstant.STASH && auditOrganization.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//
//        }
//        return super.deleteLogic(ids);
//    }
//
//    @Override
//    @YthTaskObserver
//    public boolean saveInternalAuditReportByDataSource(String date) {
//        boolean flag = true;
//        Date start = DateUtil.parse(date, DateUtil.PATTERN_DATE);
//        //获取数据
//        //List<IamInternalAuditOrganizationVO> syncDatas = ythAuditPlanService.getSyncData(start, DateUtil.plusDays(start, 1));
//        List<IamInternalAuditOrganizationVO> syncDatas = ythAuditPlanService.getSyncData(null, null);
//
//        Map<String, String> orgSourceIds = orgService.getSourceId();
//        Map<String, String> userSourceIds = userService.getSourceId();
//
//        if (CollectionUtil.isNotEmpty(syncDatas)) {
//
//            //查询数据库存在的旧数据
//            List<IamInternalAuditOrganization> allOldData = list(new LambdaQueryWrapper<IamInternalAuditOrganization>()
//                    .eq(IamInternalAuditOrganization::getDataSource, 3)
//                    .in(IamInternalAuditOrganization::getDataSourceId, syncDatas.stream().map(IamInternalAuditOrganization::getDataSourceId).collect(Collectors.toList())));
//
//            for (IamInternalAuditOrganizationVO syncData : syncDatas) {
//                //企业
//                String enterpriseId = orgSourceIds.get(syncData.getEnterpriseId());
//                if (StringUtils.isNotBlank(enterpriseId)) {
//                    syncData.setEnterpriseId(enterpriseId);
//                    syncData.setCreateCompanyId(enterpriseId);
//                }
//                if (CollectionUtil.isNotEmpty(allOldData)) {
//                    Optional<IamInternalAuditOrganization> oldOrganizationList = allOldData.stream().filter(e -> syncData.getDataSourceId().equals(e.getDataSourceId())).findFirst();
//                    if (oldOrganizationList.isPresent()) {
//                        IamInternalAuditOrganization auditOrganization = oldOrganizationList.get();
//                        auditOrganization.setEnterpriseId(enterpriseId);
//                        auditOrganization.setEnterpriseName(syncData.getEnterpriseName());
//                        auditOrganization.setInstitutionName(syncData.getInstitutionName());
//                        auditOrganization.setFullInternalAuditNum(syncData.getFullInternalAuditNum());
//                        auditOrganization.setFullTimeAuditNum(syncData.getFullTimeAuditNum());
//                        auditOrganization.setFillingYear(syncData.getFillingYear());
//                        auditOrganization.setFillingTime(syncData.getFillingTime());
//                        auditOrganization.setDesignInternalAuditFlag(syncData.getDesignInternalAuditFlag());
//                        auditOrganization.setCreateCompanyId(enterpriseId);
//                        flag = updateById(auditOrganization);
//                    } else {
//                        flag = super.saveOrUpdate(auditOrganizationWrapper.voToEntity(syncData));
//                    }
//                } else {
//                    flag = super.saveOrUpdate(auditOrganizationWrapper.voToEntity(syncData));
//                }
//            }
//        }
//        return flag;
//    }
//}
